package com.cloud.school.app.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @ClassName WebSocketConfiguration
 * @Description TODO
 * @Author 36297
 * @Date 2018/12/11 16:52
 * @Version 1.0
 */
@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {

    public static final String USER_KEY = "userId";

    @Autowired
    @Qualifier("chatWebSocketHandler")
    private WebSocketHandler chatWebSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(ChatWebSocketHandler(),"/chat/message").setAllowedOrigins("*").addInterceptors(new ParamHandshakeInterceptor());
    }

    public WebSocketHandler ChatWebSocketHandler() {
        return new ExceptionWebSocketHandlerDecorator(chatWebSocketHandler);
    }

    /**
     * @Description: 处理uerid信息
     */
    @Slf4j
    public static class ParamHandshakeInterceptor implements HandshakeInterceptor {
        @Override
        public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
            if (serverHttpRequest instanceof ServletServerHttpRequest) {
                String userId = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getParameter(USER_KEY);//获取参数
                if (!StringUtils.isEmpty(userId)) {
                    map.put(USER_KEY, userId);
                    return true;
                }
            }
            log.error("聊天请求userId不能为空");
            return false;
        }

        @Override
        public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        }
    }
}
